from course import models
from django.db.models import Q
from course.service.serializers import base_examSerializers, exam_topicIdSerializers, base_workSerializers, \
    work_topicIdSerializers


# 模糊查询
def search(keyword):
    """试卷"""
    # 对试卷相关的两张表的特定字段进行关键词查找
    examList = (models.exam.objects.filter(
        Q(exam_name__icontains=keyword) | Q(exam_type__icontains=keyword)).all())
    exam_topicList = (models.exam_topic.objects.filter(
        Q(exam_catalogue__icontains=keyword) | Q(knowledge_point__icontains=keyword)
        | Q(Bquestion_content__icontains=keyword) | Q(Squestion_content__icontains=keyword) |
        Q(program_objective__icontains=keyword)).all())
    # 对查找结果反序列化
    exam_result = base_examSerializers(instance=examList, many=True)
    # 由于返回的结果是省略表（仅含名字，类型），所以查到的详细表的内容并不可以直接返回，而是要根据两表之间的关联字段从详细表中找对应的省略表并返回省略表
    # 由于要取详细表的id，故先对相关id进行序列化操作
    topic_idResult = exam_topicIdSerializers(instance=exam_topicList, many=True)
    # 从详细表序列化对象中提取出 id 字段，放入列表中
    exam_ids = []
    for i in topic_idResult.data:
        exam_ids.append(i['exam_id'])
    # 在省略表中查找与详细表一致的id字段
    same_id = models.exam.objects.filter(exam_id__in=exam_ids)
    exam_topic_result = base_examSerializers(instance=same_id, many=True)
    """作业"""
    workList = (models.work.objects.filter(
        Q(work_name__icontains=keyword) | Q(work_type__icontains=keyword)).all())
    work_topicList = (models.work_topic.objects.filter(
        Q(work_catalogue__icontains=keyword) | Q(knowledge_point__icontains=keyword)
        | Q(Bquestion_content__icontains=keyword) | Q(Squestion_content__icontains=keyword) |
        Q(program_objective__icontains=keyword)).all())
    work_result = base_workSerializers(instance=workList, many=True)
    topic_idResult = work_topicIdSerializers(instance=work_topicList, many=True)
    # 从详细表序列化对象中提取出 id 字段，放入列表中
    work_ids = []
    for i in topic_idResult.data:
        work_ids.append(i['work_id'])
    # 在省略表中查找与详细表一致的id字段
    same_id = models.work.objects.filter(work_id__in=work_ids)
    work_topic_result = base_workSerializers(instance=same_id, many=True)
    # 合并
    merged_data = []
    merged_data.extend(exam_topic_result.data)
    merged_data.extend(exam_result.data)
    merged_data.extend(work_topic_result.data)
    merged_data.extend(work_result.data)
    return merged_data

